package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.InvRow;
import Models.InvColumn;

public class InvRowPresenter extends AbstractPresenter<InvRow> {
	final String SINGLEITEM = "invRow";
	final String MULTIITEM = "invRows";
	
	public ArrayList<InvRow> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public InvRow tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public InvRow createItemFromJSONObject(JSONObject jsonObject){
		InvRow item = new InvRow();
		try{
			if(!jsonObject.isNull("beer")){
				//create product if set
				POSBeerViewPresenter presenter = new POSBeerViewPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("beer");
				item.setBeer(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setBeer(null);
			}
			
			//Set Documents Collection
			ArrayList<InvColumn> columns = new ArrayList<InvColumn>();
			if(!jsonObject.isNull("columnCollection")){
				Object itm = jsonObject.get("columnCollection");
				InvColumnPresenter presenter = new InvColumnPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						columns.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					columns.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setColumnCollection(columns);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(InvRow item){
		try{
			JSONObject json = new JSONObject();

			if(item.getBeer()!=null){
				final POSBeerViewPresenter presenter = new POSBeerViewPresenter();
				json.put("beer", presenter.createJSON(item.getBeer()));
			} else {
				json.put("beer", JSONObject.NULL);
			}
			
			//Create Doc Collection
			if(item.getColumnCollection()!=null){
				InvColumnPresenter presenter = new InvColumnPresenter();
				if(item.getColumnCollection().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getColumnCollection().size(); i++){
						jsonArray.put(presenter.createJSON(item.getColumnCollection().get(i)));
					}
					json.put("columnCollection", jsonArray);
				}
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public InvRow getEmptyEntity(){
		InvRow entity = new InvRow();
		return entity;
	}
}
